package com.yfree.adapters;

import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;

import com.yfree.activities.YActivity;

import net.tsz.afinal.FinalActivity;

import java.util.List;

/**
 * Created by YangZhe on 2017/1/13.
 */

public abstract class YAdapter<T> extends YBaseAdapter<T> {
    public YAdapter(YActivity context, List<T> list) {
        super(context, list);
    }

    public abstract int getItemLayoutId(int position);

    public abstract ViewHolder getViewHolder(int position);

    @Override
    public final View getView(final int position, View convertView, ViewGroup viewGroup) {
        ViewHolder holder;
        if (convertView == null) {
            convertView = inflateById(getItemLayoutId(position));
            holder = getViewHolder(position);
            holder.initHolder(convertView);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }
        final T t = getItem(position);
        holder.onItemBuild(convertView, position, t);
        final View curConvertView = convertView;
        convertView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onItemClick(curConvertView, position, t);
            }
        });
        return convertView;
    }

    public void onItemClick(@NonNull View convertView, int position, @NonNull T t) {
    }

    public abstract class ViewHolder {
        void initHolder(View convertView) {
            FinalActivity.initInjectedView(this, convertView);
            onItemCreate(convertView);
        }

        public void onItemCreate(@NonNull View convertView) {
        }

        public abstract void onItemBuild(@NonNull View convertView, int position, @NonNull T t);
    }
}